import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from 'views/home/homeIndex.vue'
import Login from 'views/login/loginIndex.vue'

Vue.use(VueRouter)

function isLogin() {
  return  !!JSON.parse(sessionStorage.getItem('userInfo'))
}

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/index',
    name: 'home',
    component: Home,
  },
  {
    path: '/login',
    name:'login',
    component: Login,
  }
]

const router = new VueRouter({
  // mode: 'history',
  // base: process.env.BASE_URL,
  routes
})

// 登录鉴权 当前路由是否需要登录
router.beforeEach((to, from, next) => {
  if (!to.meta.needLogin) {
    next()
  } else {
    // 需要登录
    if (isLogin()) {
      next({
        query: {
          from
        }
      })
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  }
})

export default router
